package frog.lazy.framework.http.handler;

import frog.lazy.framework.core.exception.BizException;
import frog.lazy.framework.core.tools.StrUtils;
import frog.lazy.framework.http.annotation.LoginToken;
import frog.lazy.framework.http.constant.SystemConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理请求
 * 方法过虑：过时
 * IP白名单过虑：
 * 方法权限配置：
 * 只作全局拦截，参数校验全部给到下一层处理
 *
 */
@Slf4j
public class HttpInterceptHandler extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        StringBuffer url = request.getRequestURL();
        request.setAttribute(SystemConstant.START_TIME,System.currentTimeMillis());
        request.setAttribute(SystemConstant.SESSION_ID,request.getSession().getId());
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod)handler;

            Deprecated deprecated = handlerMethod.getMethodAnnotation(Deprecated.class);
            if(null != deprecated){
                log.warn("请求已经停用：{}",url);
                throw BizException.error("功能已经停用");
            }

            String token = request.getHeader("token");
            LoginToken loginToken = handlerMethod.getMethodAnnotation(LoginToken.class);
            if(null != loginToken && loginToken.required()){
                if(StrUtils.isBlank(token)){
                    log.warn("非法请求：{}",url);
                    throw BizException.noLogin("无效token,请重新登录");
                }
            }
//            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
//            for(MethodParameter methodParameter : methodParameters){
//                String paName = methodParameter.getParameterName();
//                // TODO 方法权限过虑
//            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView){
    }
}
